<?php

use yii\db\ActiveRecordInterface;
use yii\helpers\StringHelper;

/* @var $this yii\web\View */
/* @var $generator backend\modules\gii\generators\crud\Generator */

$controllerClass = StringHelper::basename($generator->controllerClass);
$modelClass = StringHelper::basename($generator->modelClass);
$searchModelClass = StringHelper::basename($generator->searchModelClass);
$formModelClass = StringHelper::basename($generator->formModelClass);
if ($modelClass === $searchModelClass) {
    $searchModelAlias = $searchModelClass . 'Search';
}

/* @var $class ActiveRecordInterface */
$class = $generator->modelClass;
$pks = $class::primaryKey();
$urlParams = $generator->generateUrlParams();
$actionParams = $generator->generateActionParams();
$actionParamComments = $generator->generateActionParamComments();

echo "<?php\n";
?>

namespace <?= StringHelper::dirname(ltrim($generator->controllerClass, '\\')) ?>;

use <?= ltrim($generator->modelClass, '\\') ?>;
<?php if (!empty($generator->searchModelClass)): ?>
use <?= ltrim($generator->searchModelClass, '\\') . (isset($searchModelAlias) ? " as $searchModelAlias" : "") ?>;
<?php else: ?>
use yii\data\ActiveDataProvider;
<?php endif; ?>
<?php if ($generator->formModelClass): ?>
use <?= ltrim($generator->formModelClass, '\\') ?>;
<?php endif; ?>
use <?= ltrim($generator->baseControllerClass, '\\') ?>;
use common\widgets\pages\GridViewPage;
use common\widgets\grid\BulkAjaxActionBtn;
use Yii;
use yii\filters\VerbFilter;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * <?= $controllerClass ?> implements the CRUD actions for <?= $modelClass ?> model.
 */
class <?= $controllerClass ?> extends <?= StringHelper::basename($generator->baseControllerClass) . "\n" ?>
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors = [];

        $behaviors['verbs'] = [
            'class'   => VerbFilter::className(),
            'actions' => [
                'index'             => ['get'],
                'create'            => ['get', 'post'],
                'update'            => ['get', 'put', 'post'],
                'delete'            => ['post', 'delete'],
                'batch-delete'      => ['post', 'delete'],
                'ajax-batch-delete' => ['post', 'delete'],
            ]
        ];

        return $behaviors;
    }

    /**
     * 批量删除ajax请求
     */
    public function actionAjaxBulkDelete()
    {
        return $this->ajaxBlukAction(function ($ids)
        {
            $models = $this->findModel($ids);
            foreach ($models as $model)
            {
                $model->delete();
            }
            return "删除成功!";
        });
    }

    /**
     * Lists all <?= $modelClass ?> models.
     *
     * @return mixed
     */
    public function actionIndex()
    {
<?php if (!empty($generator->searchModelClass)): ?>
        $searchModel = new <?= isset($searchModelAlias) ? $searchModelAlias : $searchModelClass ?>();
        $dataProvider = $searchModel->search(Yii::$app->request->get());

        $page = $this->createGridViewPage($dataProvider, $searchModel);
        return $page->render();
<?php else: ?>
        $dataProvider = new ActiveDataProvider([
            'query' => <?= $modelClass ?>::find(),
        ]);

        $page = $this->createGridViewPage($dataProvider);
        return $page->render();
<?php endif; ?>
    }

    /**
     * Creates a new <?= $modelClass ?> model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     *
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new <?php echo $formModelClass ?>(['scenario' => <?php echo $formModelClass ?>::SCENARIO_CREATE]);

        $model->isNewRecord = true;

        if ($model->load(Yii::$app->request->post()))
        {
            if (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            else
            {
                if ($model->save())
                {
                    Yii::$app->session->setFlash('success', '创建成功!');
                    return $this->redirect(['update', 'id' => $model->id]);
                }
                else
                {
                    Yii::$app->session->setFlash('danger', $model->formatErrors());
                    return $this->refresh();
                }
            }
        }

        $page = $this->createFormViewPage(
            $model,
            <?php echo $formModelClass ?>::SCENARIO_CREATE,
            [
                'pageTitle' => 'Update',
            ]
        );
        return $page->render();
    }

    /**
     * Updates an existing <?= $modelClass ?> model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * <?= implode("\n     * ", $actionParamComments) . "\n" ?>
     * @return mixed
     */
    public function actionUpdate(<?= $actionParams ?>)
    {
        $model = $this->findModel(<?= $actionParams ?>);
        $model->setScenario(<?= $formModelClass ?>::SCENARIO_UPDATE);

        if ($model->load(Yii::$app->request->post()))
        {
            if (Yii::$app->request->isAjax)
            {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
            else
            {
                if ($model->save())
                {
                    Yii::$app->session->setFlash('success', '更新成功!');
                }
                else
                {
                    Yii::$app->session->setFlash('danger', $model->formatErrors());
                    return $this->refresh();
                }
            }
        }

        $page = $this->createFormViewPage(
            $model,
            <?php echo $formModelClass ?>::SCENARIO_UPDATE,
            [
                'pageTitle' => 'Update',
            ]
        );
        return $page->render();
    }

    /**
     * Deletes an existing <?= $modelClass ?> model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     *
     * <?= implode("\n     * ", $actionParamComments) . "\n" ?>
     * @return mixed
     */
    public function actionDelete(<?= $actionParams ?>)
    {
        $this->findModel(<?= $actionParams ?>)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Delete multiple <?= $modelClass ?> model.
     */
    public function actionBatchDelete()
    {
        if (($ids = Yii::$app->request->post('ids')) !== null)
        {
            $models = $this->findModel($ids);
            foreach ($models as $model)
            {
                $model->delete();
            }

            return $this->redirect(['index']);
        }
        else
        {
            throw new HttpException(400);
        }
    }

    /**
     * Finds the <?= $modelClass ?> model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     *
     * <?= implode("\n     * ", $actionParamComments) . "\n" ?>
     * @return <?=                   $modelClass ?> the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel(<?= $actionParams ?>)
    {
<?php
if (count($pks) === 1) {
    $condition = '$id';
} else {
    $condition = [];
    foreach ($pks as $pk) {
        $condition[] = "'$pk' => \$$pk";
    }
    $condition = '[' . implode(', ', $condition) . ']';
}
?>
        if (($model = <?= $formModelClass ?>::findOne(<?= $condition ?>)) !== null)
        {
            return $model;
        }
        else
        {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
